﻿using BusinessLayer;
using BusinessLayer.VDataEntities;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Text;
using System.Web;
using System.Web.Mvc;
using TrialManagementTool.Helper;
using TrialManagementTool.Models;
using TrialManagmentTool.Models;

namespace TrialManagementTool.Controllers
{
    [WechatAuthentication]
    public class TrialMobileController : Controller
    {
        //
        // GET: /TrialMobile/

        public ActionResult Index()
        {
            return View();
        }

        public ActionResult TrialManagement()
        {
            return View();
        }

        public ActionResult AddNewTrial()
        {
            return View();
        }

        /// <summary>
        /// 新增试验点 只需要trialID,查看试验点需要两个参数
        /// </summary>
        /// <param name="trialID"></param>
        /// <param name="trialSiteID"></param>
        /// <returns></returns>
        public ActionResult MainData(long trialID, long? trialSiteID)
        {
            VTrialDetail detail = new VTrialDetail();
            VTrialSite data = new VTrialSite();

            if (!trialSiteID.HasValue)
            {
                //create new trial
                detail = TrialBusiness.CreateNewTrial(trialID);
            }
            else
            {
                //update trial Basic info
                detail = TrialBusiness.GetTrialDetail(trialSiteID.Value);
                data = detail.TrialSite;
            }

            List<DynamicInfoSummary> mainData = new List<DynamicInfoSummary>();
            mainData.Add(new DynamicInfoSummary { name = "Address", display = true, value = data.Address, isMandary = false, ChineseDesc = "市县/乡镇" });
            mainData.Add(new DynamicInfoSummary { name = "Partner", display = true, value = data.Partner, isMandary = true, ChineseDesc = "合作单位" });
            mainData.Add(new DynamicInfoSummary { name = "CropCategory", display = true, value = data.CropCategory, isMandary = true, ChineseDesc = "作物品种" });
            mainData.Add(new DynamicInfoSummary { name = "SeedMode", display = true, value = data.SeedMode, isMandary = true, ChineseDesc = "栽培模式" });
            string temp = "0";
            if (data.IsClosed.HasValue && data.IsClosed.Value == true) { temp = "1"; }
            mainData.Add(new DynamicInfoSummary { name = "Object", display = true, value = data.Object, isMandary = true, ChineseDesc = "靶标杂草" });
            mainData.Add(new DynamicInfoSummary { name = "IsClosed", display = true, value = temp, isMandary = true, ChineseDesc = "是否封闭" });
            mainData.Add(new DynamicInfoSummary { name = "SubCropCategory", display = true, value = data.SubCropCategory, isMandary = true, ChineseDesc = "季节(水稻早/中/晚)" });

            TrialBasicSummaryViewModel model = new TrialBasicSummaryViewModel();
            switch (detail.ProductCategory.Name)
            {
                case "除草剂":
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "防治靶标";
                    break;
                case "杀菌剂":
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "靶标病害";
                    mainData.Find(c => c.name.Equals("SeedMode")).ChineseDesc = "种植模式";
                    mainData.Find(c => c.name.Equals("SubCropCategory")).display = true;
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
                case "杀虫剂":
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "靶标害虫";
                    mainData.Find(c => c.name.Equals("SeedMode")).ChineseDesc = "种植模式";
                    mainData.Find(c => c.name.Equals("SubCropCategory")).display = true;
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
                case "肥料增效剂":
                    mainData.Find(c => c.name.Equals("Object")).display = true;
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
                default:
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "靶标病害";
                    mainData.Find(c => c.name.Equals("SeedMode")).ChineseDesc = "种植模式";
                    mainData.Find(c => c.name.Equals("SubCropCategory")).display = true;
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
            }
            model.TrialGuideID = detail.TrialGuideID.Value;
            model.dataList = mainData;
            model.ID = trialID;
            return View(model);
        }

        public ActionResult FinalReport(long ID)
        {
            VTrialSite data = TrialBusiness.GetTrialSiteDetail(ID);
            VTrialDetail detail = TrialBusiness.GetTrialDetail(data.ID);

            TrialBasicSummaryViewModel model = new TrialBasicSummaryViewModel();
            model.ID = ID;
            List<DynamicInfoSummary> mainData = new List<DynamicInfoSummary>();
            List<FinalReportDesc> descData = new List<FinalReportDesc>();
            mainData.Add(new DynamicInfoSummary { name = "LastObserveDate", display = true, value = data.LastObserveDate.HasValue == true ? data.LastObserveDate.Value.ToString("yyyy-MM-dd-HH-mm") : "", ChineseDesc = "最后一次调查时间" });
            string temp = "false";
            if (data.IsAcceptable.HasValue)
            {
                temp = data.IsAcceptable.Value.ToString();
            }
            mainData.Add(new DynamicInfoSummary { name = "IsAcceptable", display = true, value = temp, ChineseDesc = "对此药效农户是否接受" });

            temp = "0";
            if (!string.IsNullOrEmpty(data.EffectResult))
            {
                temp = data.EffectResult;
            }
            mainData.Add(new DynamicInfoSummary { name = "EffectResult", display = true, value = temp, ChineseDesc = "最后一次调查目测药效" });
            mainData.Add(new DynamicInfoSummary { name = "EffectDescription", display = true, value = data.EffectDescription, ChineseDesc = "具体药效描述(动态过程)" });
            mainData.Add(new DynamicInfoSummary { name = "CropDescription", display = true, value = data.CropDescription, ChineseDesc = "其它说明" });
            mainData.Add(new DynamicInfoSummary { name = "YieldEffect", display = true, value = data.YieldEffect, ChineseDesc = "对产量影响%(减产用负值表示)" });
            mainData.Add(new DynamicInfoSummary { name = "Comments", display = true, value = data.Comments, ChineseDesc = "备注" });
            model.dataList = mainData;
            model.TrialStatus = detail.Status;

            descData.Add(new FinalReportDesc() { ID = 1, Description = "不能接受" });
            descData.Add(new FinalReportDesc() { ID = 2, Description = "有效" });
            descData.Add(new FinalReportDesc() { ID = 3, Description = "效果好" });
            descData.Add(new FinalReportDesc() { ID = 4, Description = "效果优异" });
            model.reportDescList = descData;

            model.TrialGuideID = detail.TrialGuideID.HasValue == true ? detail.TrialGuideID.Value : 0;
            return View(model);
        }

        public ActionResult AddNewReport(long reportid)
        {
            VReport model = ReportBusiness.GetByID(reportid);
            return View(model);
        }

        public ActionResult Purpose(long id)
        {
            VTrialGuide model = TrialBusiness.GetTrialGuide(id);
            return View(model);
        }

        public ActionResult ReportManagement(long ID)
        {
            ReportViewModel model = new ReportViewModel();

            VTrialDetail detail = TrialBusiness.GetTrialDetail(ID);

            List<DynamicInfoSummary> mainData = new List<DynamicInfoSummary>();
            mainData.Add(new DynamicInfoSummary { name = "Address", display = true, value = detail.TrialSite.Address, isMandary = false, ChineseDesc = "市县/乡镇" });
            mainData.Add(new DynamicInfoSummary { name = "Partner", display = true, value = detail.TrialSite.Partner, isMandary = true, ChineseDesc = "合作单位" });
            mainData.Add(new DynamicInfoSummary { name = "CropCategory", display = true, value = detail.TrialSite.CropCategory, isMandary = true, ChineseDesc = "作物品种" });
            mainData.Add(new DynamicInfoSummary { name = "SeedMode", display = true, value = detail.TrialSite.SeedMode, isMandary = true, ChineseDesc = "栽培模式" });
            mainData.Add(new DynamicInfoSummary { name = "Object", display = true, value = detail.TrialSite.Object, isMandary = true, ChineseDesc = "靶标杂草" });
            string temp = "0";
            if (detail.TrialSite.IsClosed.HasValue && detail.TrialSite.IsClosed.Value == true) { temp = "1"; }
            mainData.Add(new DynamicInfoSummary { name = "IsClosed", display = true, value = temp, isMandary = true, ChineseDesc = "是否封闭" });
            mainData.Add(new DynamicInfoSummary { name = "SubCropCategory", display = true, value = detail.TrialSite.SubCropCategory, isMandary = true, ChineseDesc = "季节" });
            switch (detail.ProductCategory.Name)
            {
                case "除草剂":
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "防治靶标";
                    break;
                case "杀菌剂":
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "靶标病害";
                    mainData.Find(c => c.name.Equals("SeedMode")).ChineseDesc = "种植模式";
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
                case "杀虫剂":
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "靶标害虫";
                    mainData.Find(c => c.name.Equals("SeedMode")).ChineseDesc = "种植模式";
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
                case "肥料增效剂":
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
                default:
                    mainData.Find(c => c.name.Equals("Object")).ChineseDesc = "靶标病害";
                    mainData.Find(c => c.name.Equals("SeedMode")).ChineseDesc = "种植模式";
                    mainData.Find(c => c.name.Equals("SubCropCategory")).display = false;
                    mainData.Find(c => c.name.Equals("IsClosed")).display = false;
                    break;
            }
            model.dataList = mainData;
            model.title = detail.TrialSite.Address;
            model.trialDetail = detail;

            return View(model);
        }

        public ActionResult TrialDetail(long id)
        {
            return Redirect("../TrialMobile/ReportManagement?id=" + id);
        }

        public long UpdateImage(HttpPostedFileBase file)
        {
            ResponseMessage responseMessage = new ResponseMessage();
            try
            {
                string folderpath = string.Format("{0}\\{1}\\{2}\\{3}", AppDomain.CurrentDomain.BaseDirectory, "UploadImage", DateTime.Now.Year, DateTime.Now.Month);
                if (!Directory.Exists(folderpath))
                {
                    Directory.CreateDirectory(folderpath);
                }
                string path = string.Format("{0}\\{1}.jpg", folderpath, System.Guid.NewGuid());
                file.SaveAs(path);
                //step2 process Image
                Bitmap bmp = new Bitmap(path);
                MemoryStream ms = new MemoryStream();
                bmp.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
                byte[] arr = new byte[ms.Length];
                ms.Position = 0;
                ms.Read(arr, 0, (int)ms.Length);
                ms.Close();
                bmp.Dispose();
                String strbaser64 = Convert.ToBase64String(arr);
                string str = "data:image/jpeg;base64," + strbaser64;
                byte[] strBytes = Encoding.UTF8.GetBytes(str);
                string reportID = Request.Form["ReportID"];
                long imageid = ReportBusiness.AddImages(strBytes, long.Parse(reportID));
                responseMessage.message = imageid.ToString();
                responseMessage.status = ResponseType.Success.ToString();
                return imageid;
            }
            catch (Exception ex)
            {
                LogHelper.Error("UploadImage Error" + ex);
                responseMessage.status = ResponseType.Fail.ToString();
                return 0;
            }

        }

        public ActionResult ShiFandian(long id)
        {
            ViewBag.trialId = id;
            ViewBag.trialGuideID = TrialBusiness.GetTrialGuideIDByTrialID(id);
            return View();
        }

        public ActionResult ProcessManagement(long id)
        {
            VReportBasicInfo data = ReportBusiness.GetProcessBasicInfo(id);
            return View(data);
        }
    }
}
